<template>
    <div class="content">
        <el-dialog :visible.sync="batchBind.dialogFormVisible"
        title="批量发放" size="tiny" :before-close="handleClose">
            <div v-loading = "upLoading">
                <el-form ref="ruleForm" :model="ruleForm" :rules="rules" label-width="140px">
                    
                    <el-form-item label="选择发放的手机号：">
                    <el-row :gutter="20" type="flex" justify="space-between">
                        <el-col :span="14">

                            <span class="urlText" v-cloak>
                                <el-row type="flex" class="row-bg" justify="space-between">
                                <el-col :span="6">
                                    <el-button type="text" class="text">{{form.text}}</el-button>
                                </el-col>
                                <span>
                                    <el-button v-if="delStart" @click="delFileUrl" type="text">
                                    删除<i class="el-icon-close el-icon--right"></i>
                                    </el-button>
                                </span>
                                </el-row>
                                <i v-if="expand" :style="`width:${progress}%`" class="expand"></i>
                            </span>
                        </el-col>
                        <span>
                            <template>
                                <file-upload ref="upload" @onSuccess="successFn" :isAuto="true" @getFileName="getFileName"  @onProgress="progressFn" :up-file-type="fileOptions.upFileType">
                                    <el-button  type="text" class="btn-success font-style-color" slot="trigger" size="small">选择文件</el-button>
                                    <!--<el-button  type="text" class="btn-success font-style-color" slot="trigger" size="small" @click = "downloadModule">下载模板</el-button>-->
                                </file-upload>
                            </template>
                        </span>
                        <span>
                            <template>
                                <el-button  type="text" class="btn-success font-style-color" slot="trigger" size="small" @click = "downloadModule">下载模板</el-button>
                            </template>
                        </span>
                    </el-row>
                    <el-row>
                        <el-col align="left">
                            <span class="countTip">待发放激活码个数：<span v-cloak>{{count}}</span></span>
                        </el-col>
                    </el-row>
                    </el-form-item>
                    <div v-if="percentage == 100">
                        <div v-if="delStart">
                            <el-form-item label="校验结果：">
                            <p>数据无误，可上传！</p>
                            </el-form-item>
                        </div>
                    </div>
                    <div v-else>
                        <div v-if="delStart">
                            <el-form-item label="校验结果：">
                                <span class="title">数据校验中</span>
                                    <el-row :gutter="20">
                                    <el-col :span="20">
                                        <el-progress :percentage="percentage"></el-progress>
                                    </el-col>
                                    </el-row>
                                    <el-row :gutter="20">
                                    <el-col :span="20">
                                        <p>{{errorIng}}</p>
                                    </el-col>
                                    </el-row>
                            </el-form-item>
                        </div>
                    </div>
                    <div v-if="upError">
                        <el-form-item label="错误信息：">
                            <el-row :gutter="20">
                            <el-col :span="20">
                                <p>{{errorIng}}</p>
                            </el-col>
                            </el-row>
                        </el-form-item>
                    </div>
                    <!--<el-form-item>
                            <el-row :gutter="20" type="flex" justify="space-between">
                                <el-col :span="20">
                                        <span class="font-style-color" @click="downloadModule">
                                            请先选择学校、年级、班级后下载班级专属批量绑卡模板
                                        </span>
                                </el-col>
                            </el-row>
                    </el-form-item>-->
                    <!--<el-row type="flex" class="row-bg" justify="center">
                        <el-col :span="4">
                            <el-button @click="cancel('ruleForm')">关闭</el-button>
                        </el-col>
                        <el-col :span="4">
                            <el-button type="primary" :disabled="percentage !== 100" :loading="loading" @click="btnUp('ruleForm')">上传</el-button>
                        </el-col>
                    </el-row>-->
                </el-form>
                <footer>
                    <el-button @click="cancel('ruleForm')">取消</el-button>
                    <el-button :disabled="percentage !== 100" :loading="loading" @click="add('ruleForm')" type="primary">确认</el-button>
                </footer>
            </div>
        </el-dialog>
    </div>
</template>
<script>
// import { getSchoolList, getGrade } from "api/classAll";

import { getUseNum, batchActivationCodeDetailByGrantPhone, confirmBatchUpdate } from 'api/numberManagement';
import school from 'components/SchoolClasss/school';
import fileUpload from 'components/Upload/fileUpload';
import { mapGetters } from 'vuex';
export default {
    name: 'addClassSchool',
    components: { school, fileUpload },
    props: {
        batchBind: {
            type: Object,
            required: true
        }
        // fActivationCodeId
    },
    data() {
        return {

    // 设置上传类型
            fileOptions: {
                upFileType: 'excel'
            },

    // 初始加载进度
            progress: 0,

    // 展示上传文件名称
            form: {
                text: ''
            },

    // 判断是否选择文件
            delStart: false,

    // 是否进度条滚动
            expand: false,
            
    // 上传loading
            loading: false,
            disabled: false,
            percentage: 0,
            timout: null,
            errorIng: '',
            upError: false,

            count: 0,
            upLoading: false,

            autoFill: false,
            ruleForm: {
                sGrade: '',
                sClass: '',
                studentName: '',
                cardNum: '',
                sCardType: '',
                sRelationType: '',
                sRelation: ''
            },
            phoneList: [], 
            rules: {
                schoolName: [
                    { required: true, message: '请输入学校名称', trigger: 'blur' }
                ],
                studentName: [
                    { required: true, message: '请输入学生姓名', trigger: 'blur' }
                ],
                cardNum: [
                    { required: true, message: '请输入卡号', trigger: 'blur' }
                ]
            }
        };
    },
    computed: {
        ...mapGetters(['token'])
    },
    created() {
        // this.$route.params.id
        // console.log('res111', this.$route.params.id);
        getUseNum(this.$route.params.id).then(res => {
            // console.log('res222', res);
            this.count = res.data.content;
        }).catch(Error => {
            // 
        });
    },
    watch: {
        batchBind(val) {
            // console.log('111222');
        }
    },
    methods: {

        progressFn(p) {
            this.progress = p.percent;
            this.expand = true;
        },

        progressIng(boolean) {
            if (boolean) {
                this.timout = setInterval(() => {
                    if (this.percentage <= (85 + Math.round(Math.random()*10))) {
                        this.percentage += Math.round(Math.random()*6)
                    } else {
                        clearInterval(this.timout);
                    }
                }, 500)
            } else {
                clearInterval(this.timout);
            }
        },

        // 获取学校id
        schoolChange(val) {
            // this.queryAllGrade(val);
            this.ruleForm.schoolId = val;
        },

        // 判断是否普通学校/培训学校
        judgmentSta(val) {
            this.schoolList.forEach(item => {
                if (val === item.schoolId) {
                    this.schoolType = item.schoolType;
                }
            });
        },

        // 年级列表
        queryAllGrade(val) {
            // 判断用户是否确认选择
            if (val) {
                // this.judgmentSta(val);
            }

            this.autoFill = true;
            this.$nextTick(() => {
                this.autoFill = false;
            });
            this.getGradeName = '';
            this.newSchoolId = val;
            if (val) {
                getGrade(!val ? null : val).then(response => {
                    this.gradeList = response.data.content;
                });
            }
        },

        successFn(obj) {
            // 判断是否拿到回调值
            this.upError = false;
            this.fileObj=obj;
            this.progressIng(true);

            // 触发上传事件
            // if (!this.form.text) {
            //     this.$message({
            //         message: '请先上传文件',
            //         type: 'warning'
            //     });
            // } else {
            this.loading = true;
            // fActivationCodeId
            batchActivationCodeDetailByGrantPhone(this.fileObj.fileName, this.fileObj.imgUrl, this.$route.params.id).then(response => {
                if (response.data.content.length) {
                    this.phoneList = response.data.content;
                    // response.data.content.forEach(item => {
                    //     this.phoneList.push(item);
                    // });
                }
                this.loading = false;
                this.percentage = 100;
                this.progressIng(false);
                
            }).catch(Error => {
                this.errorIng = Error;
                this.progressIng(false);
            });
        },
        getFileName(obj) {
            this.form.text = obj.name;
            this.delStart = true;
        },

        delFileUrl() {
            // this.ruleForm.schoolId = '';
            // this.ruleForm.schoolName = '';// 清空学校
            this.form.text = '';
            this.delStart = false;
            this.expand = false;
            this.loading = false;
            // this.disabled = false;
            clearInterval(this.timout);
            this.percentage = 0;
            this.upError = false;
        },

        downloadModule() {
            window.location = `${LOCAL_API.fyq}/vip/exportExcel?token=${this.token}`;
        },

        createStateFilter(query) {
            return state => {
                state.value = state.schoolName;
                return state.value.toLowerCase().includes(query.toLowerCase());
            };
        },

        handleClose() {
            this.$refs.ruleForm.resetFields();
            this.delFileUrl();
            this.ruleForm.schoolId = '';
            this.batchBind.dialogFormVisible = false;
        },

        add(ruleForm) {
            this.$refs[ruleForm].validate(valid => {
                if (!valid) {
                    return false;
                } else {
                    this.upLoading = true;
                     
                    confirmBatchUpdate(this.$route.params.id, this.phoneList).then((res) => {
                        this.upLoading = false;
                        this.$message({
                            message: '发放成功！',
                            type: 'success'
                        });
                        this.cancel();
                        this.$emit('bindState');
                    })
                    .catch(Error => {
                        this.upLoading = false;
                        // this.$message(Error);
                    });
                
                }
            });
        },

        cancel() {
            this.$refs.ruleForm.resetFields();
            this.delFileUrl();
            this.ruleForm.schoolId = '';
            this.batchBind.dialogFormVisible = false;
        }
    }
};
</script>
<style lang="scss" scoped>
.title {
  display: block;
  text-align: left;
  margin-left: 20px;
  font-size: 14px;
  margin-bottom: 18px;
  color: #333;
  position: relative;
  &::after {
    position: absolute;
    width: 4px;
    height: 14px;
    background: #ff5e2c;
    left: -15px;
    top: 10px;
    content: "";
  }
}
.tip{
  padding: 5px 0;
  color: #ccc;
  line-height: 18px;
}
.countTip{
    position: relative;
    top: 0;
    left: 0;
    color: #999;
    cursor: pointer;
    span{
        color: #333;
    }
}
.urlText {
  position: relative;
  height: 36px;
  width: 100%;
  display: block;
  border: 1px solid rgb(217, 200, 191);
  padding: 0 10px;
  transition: border-color 0.2s cubic-bezier(0.645, 0.045, 0.355, 1);
  .text {
    width: 155px;
    display: inline-block;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
  }
  .expand {
    position: absolute;
    width: 100%;
    height: 1px;
    margin: 2px 0;
    background: #37a1fb;
    bottom: -3px;
    left: 0;
    transition: all 5s;
  }
}
footer {
  text-align: center;
}
</style>
